#include <list.h>
#include <stdatomic.h>

struct semaphore {
	atomic_flag lock;
	int count;
	struct list_head wait_list;	
};

// 申请信号量
void down(struct semaphore *sem) {
	while (atomic_flag_test_and_set(&sem->lock));
	
	sem->count--;
	
	if (sem->count < 0) {
		list_add_tail(&sem->wait_list, current_thread);
		atomic_flag_clear(&sem->lock);
		park();
	} else {	
		atomic_flag_clear(&sem->lock);
	}

}

// 释放信号量
void up(struct semaphore *sem) {
    while (atomic_flag_test_and_set(&sem->lock));

    sem->count++;
	
    if (sem->count <= 0){
    	wait_thread = list_first_entry(&sem->wait_list);
		list_del_first(&sem->wait_list);
		unpark(wait_thread);
	}

   	atomic_flag_clear(&sem->lock);
}

